package com.onethinker.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.onethinker.common.constants.OneThinkerConfigConstant;
import com.onethinker.common.constants.ProjectConstant;
import com.onethinker.common.utils.UploadFileUtils;
import com.onethinker.service.UploadPicService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: yangyouqi
 * @Date: 2022/4/2 15:10
 * @Description:
 */
@Service
@Log4j2
class TencentCloudSavePicImpl implements UploadPicService {

    @Resource
    private OneThinkerConfigConstant oneThinkerConfigConstant;

    @Override
    public JSONObject uploadPic(HttpServletRequest request, String... uploadPath) {
        // 初始化腾讯云对象存储
        COSClient cosClient = initTencentCloudCos();
        List<String> uploadPicNames = new ArrayList<>();
        try {
            // 获取multipartFile文件信息
//            MultipartFile multipartFile = UploadFileUtils.getMultipartFile(request);
            List<MultipartFile> multipartFiles = UploadFileUtils.getMultipartFiles(request);
            for (MultipartFile multipartFile : multipartFiles) {
                // 指定要上传到 COS 上对象键 (也是最终访问地址)
                String uploadPicName = UploadFileUtils.getUploadPicName(multipartFile.getOriginalFilename(), uploadPath,oneThinkerConfigConstant.picConfig.tencentCloud.defaultPath);
                // 获取临时File文件并进行上传
                File localFile = UploadFileUtils.getPicTempFile(multipartFile);
                // 上传到腾讯云存储对象中
                PutObjectRequest putObjectRequest = new PutObjectRequest(oneThinkerConfigConstant.picConfig.tencentCloud.bucketName, uploadPicName, localFile);
                cosClient.putObject(putObjectRequest);
                uploadPicNames.add(uploadPicName);
            }
        } catch (CosClientException | IOException e) {
            log.error("腾讯云文件上传异常：" + e.getCause());
        } finally {
            //关闭客户端(关闭后台线程)
            cosClient.shutdown();
        }
        // 返回相关上传文件信息
        return UploadFileUtils.getSavePicBaseInfo(uploadPicNames,oneThinkerConfigConstant.picConfig.tencentCloud.host, ProjectConstant.PIC_SAVE_TENCENT_COS);
    }

    /**
     * 初始化并生成cos客户端
     * @return
     */
    private COSClient initTencentCloudCos() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(oneThinkerConfigConstant.picConfig.tencentCloud.secretId, oneThinkerConfigConstant.picConfig.tencentCloud.secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        ClientConfig clientConfig = new ClientConfig(new Region(oneThinkerConfigConstant.picConfig.tencentCloud.regionName));
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }
}
